package com.itheima.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.util.Base64Util;
import com.google.gson.Gson;
import com.itheima.common.utils.IdWorker;

import com.itheima.system.pojo.User;
import com.itheima.system.pojo.baiduAi.FaceLoginResult;
import com.itheima.system.pojo.baiduAi.QRCode;
import com.itheima.system.service.FaceLoginService;
import com.itheima.system.service.UserService;
import com.itheima.system.utils.BaiDuAiUtils;
import com.itheima.system.utils.QRCodeUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author qiankaofei
 * @version 1.0
 * @date 2020/11/25 20:44
 */
@Service
public class FaceLoginServiceImpl implements FaceLoginService {

    @Value("${qr.url}")
    private String url;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private QRCodeUtils qrCodeUtils;

    private static final Long QRCODETIME=10L;

    @Autowired
    private BaiDuAiUtils baiDuAiUtils;

    @Autowired
    private UserService userService;

    /**
     * 创建二维码
     * @return
     * @throws Exception
     */
    @Override
    public QRCode getQRCode() throws Exception {
        String code=String.valueOf(idWorker.nextId());
        String content=url+"?code="+code;
        //生成二维码
        String file = qrCodeUtils.crateQRCode(content);
        System.out.println("file = " + file);
        //将二维码的状态存入Redis(二维码的有效期设置为30分钟，初始状态设置为-1,-1未扫描)
        FaceLoginResult result=new FaceLoginResult("-1");
        String json = JSON.toJSONString(result);
        redisTemplate.opsForValue().set(getCacheKey(code),json,QRCODETIME,TimeUnit.MINUTES);
        return new QRCode(code,file);
    }

    /**
     * 根据唯一标识，查询用户是否登录成功
     */
    @Override
    public FaceLoginResult checkQRCode(String code) {
        return  new Gson().fromJson(redisTemplate.opsForValue().get(getCacheKey(code)),FaceLoginResult.class);
    }

    /**
     * 扫描二维码后，使用拍摄照片进行登录
     */
    @Override
    public String loginByFace(String code, MultipartFile file) throws IOException, JSONException {
        //调用百度AI搜索人脸
        String userId = baiDuAiUtils.faceSearch(Base64Util.encode(file.getBytes()));
        //默认是扫描失败的
        FaceLoginResult result=new FaceLoginResult("0");
        if(StringUtils.isNotBlank(userId)){
            //模拟登录过程
            User user = userService.findUserById(userId);
            if(user!=null){
                //调用登录
                String tokenInfo = userService.login(user);
                //修改二维码的状态
                result=new FaceLoginResult("1",tokenInfo,userId);
            }
        }
        //修改后的二维码状态存入Redis
        redisTemplate.opsForValue().set(getCacheKey(code), JSON.toJSONString(result),QRCODETIME,TimeUnit.MINUTES);
        return userId;
    }

    /**
     * 构造缓存key
     */
    @Override
    public String getCacheKey(String code) {
        return "qrcode_" + code;
    }

}
